<template>
  <div class="file-detection-container">
    <el-card class="page-card">
      <template #header>
        <div class="page-header">
          <span>文件检测</span>
        </div>
      </template>
      
      <!-- 检测类型切换 -->
      <el-tabs v-model="activeTab" class="detection-tabs">
        <!-- 图像检测 -->
        <el-tab-pane label="图像检测" name="image">
          <div class="detection-panel">
            <!-- 图像上传区域 -->
            <div class="upload-section">
              <el-upload
                class="image-uploader"
                :auto-upload="false"
                :on-change="handleImageChange"
                :before-upload="beforeImageUpload"
                list-type="picture-card"
                accept="image/*"
                :limit="1"
                :on-exceed="handleExceed"
              >
                <el-icon class="el-icon--upload"><Plus /></el-icon>
                <div class="el-upload__text">点击或拖拽文件到此区域上传</div>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传 JPG、PNG 或 WEBP 格式的图片，大小不超过 10MB
                  </div>
                </template>
              </el-upload>
              
              <el-button 
                type="primary" 
                class="detection-btn"
                :disabled="!selectedImageFile"
                @click="startImageDetection"
              >
                <el-icon><Search /></el-icon>
                开始检测
              </el-button>
            </div>
            
            <!-- 检测结果区域 -->
            <div v-if="imageDetectionResult" class="result-section">
              <el-card class="result-card">
                <template #header>
                  <div class="result-header">
                    <span>检测结果</span>
                  </div>
                </template>
                
                <!-- 检测结果图像 -->
                <div class="result-image-container">
                  <img 
                    :src="imageDetectionResult.imageUrl" 
                    :alt="'检测结果 - ' + selectedImageFile.name"
                    class="result-image"
                  />
                </div>
                
                <!-- 检测统计 -->
                <div class="detection-stats">
                  <el-card class="stat-card">
                    <div class="stat-content">
                      <div class="stat-icon success">
                        <el-icon class="icon-large"><Car /></el-icon>
                      </div>
                      <div class="stat-info">
                        <div class="stat-value">{{ imageDetectionResult.vehicleCount || 0 }}</div>
                        <div class="stat-label">检测到车辆</div>
                      </div>
                    </div>
                  </el-card>
                  
                  <el-card class="stat-card">
                    <div class="stat-content">
                      <div class="stat-icon warning">
                        <el-icon class="icon-large"><Warning /></el-icon>
                      </div>
                      <div class="stat-info">
                        <div class="stat-value">{{ imageDetectionResult.violationCount || 0 }}</div>
                        <div class="stat-label">违规行为</div>
                      </div>
                    </div>
                  </el-card>
                </div>
                
                <!-- 检测详情列表 -->
                <el-table 
                  v-if="imageDetectionResult.detections && imageDetectionResult.detections.length > 0"
                  :data="imageDetectionResult.detections" 
                  style="width: 100%"
                  class="detection-table"
                >
                  <el-table-column prop="type" label="类型" width="120" />
                  <el-table-column prop="confidence" label="置信度" width="100">
                    <template #default="{ row }">
                      {{ formatConfidence(row.confidence) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="violation" label="违规类型" width="120">
                    <template #default="{ row }">
                      <el-tag v-if="row.violation" type="danger">{{ row.violation }}</el-tag>
                      <span v-else class="text-muted">-</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="description" label="描述" />
                </el-table>
                
                <div v-else class="no-detections">
                  <el-empty description="未检测到任何对象" />
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 视频检测 -->
        <el-tab-pane label="视频检测" name="video">
          <div class="detection-panel">
            <!-- 视频上传区域 -->
            <div class="upload-section">
              <el-upload
                class="video-uploader"
                :auto-upload="false"
                :on-change="handleVideoChange"
                :before-upload="beforeVideoUpload"
                accept="video/*"
                :limit="1"
                :on-exceed="handleExceed"
              >
                <el-icon class="el-icon--upload"><VideoPlay /></el-icon>
                <div class="el-upload__text">点击或拖拽视频文件到此区域上传</div>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传 MP4、AVI 或 MOV 格式的视频，大小不超过 200MB
                  </div>
                </template>
              </el-upload>
              
              <el-button 
                type="primary" 
                class="detection-btn"
                :disabled="!selectedVideoFile"
                @click="startVideoDetection"
              >
                <el-icon><Search /></el-icon>
                开始检测
              </el-button>
            </div>
            
            <!-- 视频预览和检测结果 -->
            <div v-if="selectedVideoFile && !videoDetectionResult" class="preview-section">
              <video 
                ref="videoPreview"
                controls
                class="video-preview"
              >
                您的浏览器不支持视频播放
              </video>
            </div>
            
            <!-- 视频检测结果 -->
            <div v-if="videoDetectionResult" class="result-section">
              <el-card class="result-card">
                <template #header>
                  <div class="result-header">
                    <span>检测结果</span>
                    <el-button type="text" @click="downloadVideoReport">
                      <el-icon><Download /></el-icon>
                      导出报告
                    </el-button>
                  </div>
                </template>
                
                <!-- 检测统计 -->
                <div class="video-detection-stats">
                  <el-card class="stat-card">
                    <div class="stat-content">
                      <div class="stat-icon success">
                        <el-icon class="icon-large"><Car /></el-icon>
                      </div>
                      <div class="stat-info">
                        <div class="stat-value">{{ videoDetectionResult.totalVehicles || 0 }}</div>
                        <div class="stat-label">总检测车辆</div>
                      </div>
                    </div>
                  </el-card>
                  
                  <el-card class="stat-card">
                    <div class="stat-content">
                      <div class="stat-icon warning">
                        <el-icon class="icon-large"><Warning /></el-icon>
                      </div>
                      <div class="stat-info">
                        <div class="stat-value">{{ videoDetectionResult.totalViolations || 0 }}</div>
                        <div class="stat-label">总违规次数</div>
                      </div>
                    </div>
                  </el-card>
                  
                  <el-card class="stat-card">
                    <div class="stat-content">
                      <div class="stat-icon primary">
                        <el-icon class="icon-large"><Clock /></el-icon>
                      </div>
                      <div class="stat-info">
                        <div class="stat-value">{{ videoDetectionResult.processingTime || 0 }}s</div>
                        <div class="stat-label">处理时长</div>
                      </div>
                    </div>
                  </el-card>
                </div>
                
                <!-- 违规时间点列表 -->
                <div class="violation-timeline">
                  <h4 class="section-title">违规时间点</h4>
                  <div v-if="videoDetectionResult.violations && videoDetectionResult.violations.length > 0">
                    <el-timeline>
                      <el-timeline-item 
                        v-for="(violation, index) in videoDetectionResult.violations" 
                        :key="index"
                        :timestamp="formatTime(violation.timestamp)"
                        type="danger"
                        placement="top"
                      >
                        <el-card>
                          <div class="violation-item">
                            <div class="violation-info">
                              <h5>{{ violation.violationType }}</h5>
                              <p>{{ violation.description }}</p>
                            </div>
                            <img 
                              :src="violation.snapshotUrl" 
                              :alt="'违规截图 - ' + violation.timestamp"
                              class="violation-snapshot"
                              @click="playVideoAt(violation.timestamp)"
                            />
                          </div>
                        </el-card>
                      </el-timeline-item>
                    </el-timeline>
                  </div>
                  <div v-else class="no-violations">
                    <el-empty description="未检测到违规行为" />
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 检测进度对话框 -->
    <el-dialog
      v-model="detectionProgressVisible"
      title="检测进行中"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      show-close="false"
    >
      <div class="progress-container">
        <el-progress 
          :percentage="detectionProgress" 
          :status="detectionProgressStatus"
          :stroke-width="20"
        />
        <div class="progress-text">{{ detectionProgressText }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  Plus, 
  Search, 
  VideoPlay, 
  Download, 
  Van, 
  Warning, 
  Clock 
} from '@element-plus/icons-vue'
import { api } from '../api/apiService'

export default {
  name: 'FileDetection',
  components: {
    Plus,
    Search,
    VideoPlay,
    Download,
    Car: Van,
    Warning,
    Clock
  },
  setup() {
    const activeTab = ref('image')
    const selectedImageFile = ref(null)
    const selectedVideoFile = ref(null)
    const imageDetectionResult = ref(null)
    const videoDetectionResult = ref(null)
    const videoPreview = ref(null)
    const detectionProgressVisible = ref(false)
    const detectionProgress = ref(0)
    const detectionProgressStatus = ref('success')
    const detectionProgressText = ref('')
    
    // 处理图像文件变化
    const handleImageChange = (file, fileList) => {
      selectedImageFile.value = file
      imageDetectionResult.value = null
    }
    
    // 处理视频文件变化
    const handleVideoChange = (file, fileList) => {
      selectedVideoFile.value = file
      videoDetectionResult.value = null
      
      // 显示视频预览
      nextTick(() => {
        if (videoPreview.value && file.raw) {
          const videoUrl = URL.createObjectURL(file.raw)
          videoPreview.value.src = videoUrl
          videoPreview.value.load()
        }
      })
    }
    
    // 图像上传前验证
    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        ElMessage.error('请上传图像文件！')
        return false
      }
      
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        ElMessage.error('上传图片大小不能超过 10MB！')
        return false
      }
      
      return true
    }
    
    // 视频上传前验证
    const beforeVideoUpload = (file) => {
      const isVideo = file.type.startsWith('video/')
      if (!isVideo) {
        ElMessage.error('请上传视频文件！')
        return false
      }
      
      const isLt200M = file.size / 1024 / 1024 < 200
      if (!isLt200M) {
        ElMessage.error('上传视频大小不能超过 200MB！')
        return false
      }
      
      return true
    }
    
    // 处理文件超出限制
    const handleExceed = (files, fileList) => {
      ElMessage.warning(`当前限制只能上传 1 个文件`)
    }
    
    // 开始图像检测
    const startImageDetection = async () => {
      if (!selectedImageFile.value) {
        ElMessage.warning('请先上传图像文件')
        return
      }
      
      try {
        // 显示进度对话框
        detectionProgressVisible.value = true
        detectionProgress.value = 0
        detectionProgressText.value = '准备检测...'
        
        // 创建FormData
        const formData = new FormData()
        formData.append('file', selectedImageFile.value.raw)
        
        // 模拟进度更新
        simulateProgress()
        
        // 由于后端可能还未实现文件检测接口，这里使用模拟数据
        await new Promise(resolve => setTimeout(resolve, 3000))
        
        // 模拟检测结果
        const mockResult = getMockImageDetectionResult()
        imageDetectionResult.value = mockResult
        
        // 在实际项目中，应该调用API进行检测
        // const result = await api.detection.detectImage(formData)
        // imageDetectionResult.value = result
        
        detectionProgress.value = 100
        detectionProgressText.value = '检测完成！'
        
        setTimeout(() => {
          detectionProgressVisible.value = false
        }, 500)
        
        ElMessage.success('图像检测完成')
      } catch (error) {
        console.error('图像检测失败:', error)
        ElMessage.error('检测失败，请重试')
        detectionProgressVisible.value = false
      }
    }
    
    // 开始视频检测
    const startVideoDetection = async () => {
      if (!selectedVideoFile.value) {
        ElMessage.warning('请先上传视频文件')
        return
      }
      
      try {
        // 显示进度对话框
        detectionProgressVisible.value = true
        detectionProgress.value = 0
        detectionProgressText.value = '准备检测...'
        
        // 创建FormData
        const formData = new FormData()
        formData.append('file', selectedVideoFile.value.raw)
        
        // 模拟进度更新
        simulateProgress()
        
        // 由于后端可能还未实现文件检测接口，这里使用模拟数据
        await new Promise(resolve => setTimeout(resolve, 5000))
        
        // 模拟检测结果
        const mockResult = getMockVideoDetectionResult()
        videoDetectionResult.value = mockResult
        
        // 在实际项目中，应该调用API进行检测
        // const result = await api.detection.detectVideo(formData)
        // videoDetectionResult.value = result
        
        detectionProgress.value = 100
        detectionProgressText.value = '检测完成！'
        
        setTimeout(() => {
          detectionProgressVisible.value = false
        }, 500)
        
        ElMessage.success('视频检测完成')
      } catch (error) {
        console.error('视频检测失败:', error)
        ElMessage.error('检测失败，请重试')
        detectionProgressVisible.value = false
      }
    }
    
    // 模拟检测进度
    const simulateProgress = () => {
      let progress = 0
      const interval = setInterval(() => {
        progress += Math.random() * 10
        if (progress >= 90) {
          clearInterval(interval)
        }
        detectionProgress.value = Math.min(progress, 90)
        
        // 更新进度文本
        if (detectionProgress.value < 30) {
          detectionProgressText.value = '正在准备检测...'
        } else if (detectionProgress.value < 60) {
          detectionProgressText.value = '正在进行目标检测...'
        } else {
          detectionProgressText.value = '正在分析结果...'
        }
      }, 300)
    }
    
    // 获取模拟图像检测结果
    const getMockImageDetectionResult = () => {
      // 创建图像预览URL
      const reader = new FileReader()
      reader.readAsDataURL(selectedImageFile.value.raw)
      
      return {
        imageUrl: URL.createObjectURL(selectedImageFile.value.raw),
        vehicleCount: 3,
        violationCount: 1,
        detections: [
          {
            type: 'car',
            confidence: 0.98,
            violation: '闯红灯',
            description: '黑色轿车在红灯时通过路口'
          },
          {
            type: 'car',
            confidence: 0.95,
            violation: null,
            description: '白色轿车正常行驶'
          },
          {
            type: 'car',
            confidence: 0.92,
            violation: null,
            description: '银色SUV正常等待红灯'
          }
        ],
        timestamp: new Date().toISOString()
      }
    }
    
    // 获取模拟视频检测结果
    const getMockVideoDetectionResult = () => {
      return {
        totalVehicles: 24,
        totalViolations: 3,
        processingTime: 4.5,
        violations: [
          {
            timestamp: '00:01:23',
            violationType: '超速',
            description: '红色轿车在限速60km/h的路段速度达到85km/h',
            snapshotUrl: '/violation-snapshot-1.jpg'
          },
          {
            timestamp: '00:03:45',
            violationType: '违规变道',
            description: '蓝色SUV实线变道',
            snapshotUrl: '/violation-snapshot-2.jpg'
          },
          {
            timestamp: '00:05:12',
            violationType: '违规停车',
            description: '白色货车在禁止停车区域停车',
            snapshotUrl: '/violation-snapshot-3.jpg'
          }
        ],
        timestamp: new Date().toISOString()
      }
    }
    
    // 格式化置信度
    const formatConfidence = (confidence) => {
      if (typeof confidence !== 'number') return '-'
      return (confidence * 100).toFixed(1) + '%'
    }
    
    // 格式化时间
    const formatTime = (time) => {
      return time
    }
    
    // 在指定时间点播放视频
    const playVideoAt = (time) => {
      if (!videoPreview.value) return
      
      // 解析时间格式 "mm:ss" 或 "hh:mm:ss"
      const parts = time.split(':').map(Number)
      let seconds = 0
      
      if (parts.length === 3) {
        // hh:mm:ss
        seconds = parts[0] * 3600 + parts[1] * 60 + parts[2]
      } else if (parts.length === 2) {
        // mm:ss
        seconds = parts[0] * 60 + parts[1]
      }
      
      videoPreview.value.currentTime = seconds
      videoPreview.value.play()
    }
    
    // 下载视频检测报告
    const downloadVideoReport = () => {
      // 在实际项目中，这里应该生成并下载报告文件
      ElMessage.success('报告导出功能开发中')
    }
    
    // 组件卸载时清理资源
    const cleanup = () => {
      if (videoPreview.value && videoPreview.value.src) {
        URL.revokeObjectURL(videoPreview.value.src)
      }
    }
    
    onMounted(() => {
      // 组件挂载后的初始化代码
    })
    
    return {
      activeTab,
      selectedImageFile,
      selectedVideoFile,
      imageDetectionResult,
      videoDetectionResult,
      videoPreview,
      detectionProgressVisible,
      detectionProgress,
      detectionProgressStatus,
      detectionProgressText,
      handleImageChange,
      handleVideoChange,
      beforeImageUpload,
      beforeVideoUpload,
      handleExceed,
      startImageDetection,
      startVideoDetection,
      formatConfidence,
      formatTime,
      playVideoAt,
      downloadVideoReport
    }
  }
}
</script>

<style scoped>
.file-detection-container {
  padding-bottom: 20px;
}

.page-card {
  margin-bottom: 0;
}

.page-header {
  font-size: 16px;
  font-weight: 600;
}

.detection-tabs {
  margin-top: 20px;
}

.detection-panel {
  padding: 20px;
}

.upload-section {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 30px;
}

.image-uploader {
  width: 300px;
}

.video-uploader {
  width: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  padding: 40px 20px;
  text-align: center;
  transition: border-color 0.3s;
}

.video-uploader:hover {
  border-color: #409eff;
}

.detection-btn {
  margin-top: 20px;
  height: 40px;
}

.preview-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.video-preview {
  max-width: 100%;
  max-height: 400px;
  border-radius: 4px;
}

.result-section {
  margin-top: 30px;
}

.result-card {
  margin-bottom: 0;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
}

.result-image-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.result-image {
  max-width: 100%;
  max-height: 400px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.detection-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.video-detection-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  margin-right: 16px;
  padding: 10px;
  border-radius: 50%;
  font-size: 24px;
}

.stat-icon.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.stat-icon.warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.stat-icon.primary {
  background-color: #ecf5ff;
  color: #409eff;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 4px;
}

.detection-table {
  margin-top: 20px;
}

.text-muted {
  color: #909399;
}

.no-detections,
.no-violations {
  padding: 40px 0;
}

.progress-container {
  padding: 20px 0;
}

.progress-text {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #606266;
}

.violation-timeline {
  margin-top: 30px;
}

.section-title {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
}

.violation-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.violation-info {
  flex: 1;
}

.violation-info h5 {
  margin: 0 0 5px 0;
  font-size: 14px;
  font-weight: 600;
}

.violation-info p {
  margin: 0;
  font-size: 13px;
  color: #606266;
}

.violation-snapshot {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.violation-snapshot:hover {
  transform: scale(1.1);
}
</style>